﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.Security;

namespace RegulatoryPlatform.Tools
{
    public static class Util
    {
        /// <summary>
        /// 过滤证书
        /// </summary>
        public static void SetCertificatePoliy()
        {
            ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
        }

        private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            return true;
        }

        #region 加解密
        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="codeName">加密采用的编码方式</param>
        /// <param name="source">待加密的明文</param>
        /// <returns></returns>
        public static string EncodeBase64(Encoding encode, string source)
        {
            string enstring = "";
            byte[] bytes = encode.GetBytes(source);
            try
            {
                enstring = Convert.ToBase64String(bytes);
            }
            catch
            {
                enstring = source;
            }
            return enstring;
        }

        /// <summary>
        /// Base64加密，采用utf8编码方式加密
        /// </summary>
        /// <param name="source">待加密的明文</param>
        /// <returns>加密后的字符串</returns>
        public static string EncodeBase64(string source)
        {
            return EncodeBase64(Encoding.UTF8, source);
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="codeName">解密采用的编码方式，注意和加密时采用的方式一致</param>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(Encoding encode, string result)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encode.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }

        /// <summary>
        /// Base64解密，采用utf8编码方式解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(string result)
        {
            return DecodeBase64(Encoding.UTF8, result);
        }

        private static byte[] Keys = { 0x12, 0x34, 0x56, 0x87, 0x09, 0xBA, 0xCD, 0xEF };
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string EncryptDES(string encryptString, string encryptKey)
        {
            try
            {
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                dCSP.Key = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(encryptKey, "md5").Substring(0, 8));
                dCSP.IV = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(encryptKey, "md5").Substring(0, 8));
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }
        
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string DecryptDES(string decryptString, string decryptKey)
        {
            try
            {
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                DCSP.Key = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(decryptKey, "md5").Substring(0, 8));
                DCSP.IV = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(decryptKey, "md5").Substring(0, 8));
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }

        /// <summary>
        /// MD5签名加密法
        /// </summary>
        /// <param name="ConvertString"></param>
        /// <param name="decryptKey"></param>
        /// <returns></returns>
        public static string GetMd5Str(string ConvertString, string decryptKey)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString + decryptKey)), 4, 8);
            t2 = t2.Replace("-", "");
            return t2 + ConvertString;
        }
        /// <summary>
        /// MD5验证签名
        /// </summary>
        /// <param name="ConvertString"></param>
        /// <param name="decryptKey"></param>
        /// <returns></returns>
        public static string GetMd5Decryp(string ConvertString, string decryptKey)
        {
            string tempHead = ConvertString.Substring(0, 16);
            string temp = ConvertString.Substring(16, ConvertString.Length - 16);
            if (GetMd5(temp, decryptKey) == tempHead)
            {
                return temp;
            }
            else
                return "";
        }
        private static string GetMd5(string ConvertString, string decryptKey)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString + decryptKey)), 4, 8);
            t2 = t2.Replace("-", "");
            return t2;
        }

        /// <summary>
        /// 异或运算
        /// </summary>
        /// <param name="parmObj1">字符长度短的</param>
        /// <param name="parmObj2">字符长度长的，或者两入参长度一样</param>
        /// <returns></returns>
        public static string Getxor(string parmObj1, string parmObj2)
        {
            string result = "";
            byte[] ct = Encoding.UTF8.GetBytes(parmObj1);
            byte[] pd = Encoding.UTF8.GetBytes(parmObj2);
            byte[] rBytes = new byte[ct.Length];
            for (int i = 0; i < ct.Length; i++)
            {
                rBytes[i] = (byte)(ct[i] ^ pd[i]);
            }
            result = Convert.ToBase64String(rBytes);
            return result;
        }

        /// <summary>
        /// SHA256加密
        /// </summary>
        /// <param name="ConvertString"></param>
        /// <returns></returns>
        public static string GetSHA256Str(string ConvertString)
        {
            string result = "";
            SHA256 sha256 = new SHA256Managed();
            byte[] utf8Byte = sha256.ComputeHash(Encoding.UTF8.GetBytes(ConvertString));
            result = Convert.ToBase64String(utf8Byte);
            return result;
        }
        /// <summary>
        ///  AES 加密
        /// </summary>
        /// <param name="str">明文（待加密）</param>
        /// <returns></returns>
        public static string AesEncrypt(string str)
        {
            string EncryptionKey = "$LC$";
            //密文
            string key = System.Web.Configuration.WebConfigurationManager.AppSettings["AESKey"];
            if (string.IsNullOrEmpty(key) || str.StartsWith("$LC$") || str.EndsWith("$LC$"))
            {
                return str;
            }
            if (string.IsNullOrEmpty(str)) return "";
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };
            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            var encryptedValue = Convert.ToBase64String(resultArray, 0, resultArray.Length);
            return EncryptionKey + encryptedValue + EncryptionKey;
        }

        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str">明文（待解密）</param>
        /// <returns></returns>
        public static string AesDecrypt(string str)
        {
            string EncryptionKey = "$LC$";
            //密文
            string key = System.Web.Configuration.WebConfigurationManager.AppSettings["AESKey"];
            if (string.IsNullOrEmpty(key) || !str.StartsWith("$LC$"))
            {
                return str;
            }
            if (string.IsNullOrEmpty(str)) return "";
            if (!string.IsNullOrEmpty(str) && str.StartsWith(EncryptionKey) && str.EndsWith(EncryptionKey))
            {
                str = str.Substring(4, str.Length - 8);
                Byte[] toEncryptArray = Convert.FromBase64String(str);
                System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
                {
                    Key = Encoding.UTF8.GetBytes(key),
                    Mode = System.Security.Cryptography.CipherMode.ECB,
                    Padding = System.Security.Cryptography.PaddingMode.PKCS7
                };
                System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
                Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                return Encoding.UTF8.GetString(resultArray);
            }
            else
            {
                return str;
            }
        }
        #endregion 加解密
    }
}